<template>
  <div id="sub-table-item">
    <div class="filter-container">
      <el-button v-waves type="primary" size="mini" icon="el-icon-plus" @click="handleCreate">Add</el-button>
    </div>
    <el-table
      :key="tableKey"
      ref="dragSubTableRef"
      v-loading="loading"
      element-loading-text="请给我点时间！"
      :data="list"
      fit
      border
      row-key="id"
      style="width: 100%"
    >
      <el-table-column label="ID" prop="index" type="index" align="center" />
      <el-table-column
        label="Click"
        prop="click"
        align="center"
        min-width="100"
        show-overflow-tooltip
      >
        <template slot-scope="{row}">
          <span v-if="row.click" style="color:#1890ff;white-space: nowrap;">
            <a :href="row.click">{{ row.click }}</a>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="Pict" prop="pict" align="center">
        <template slot-scope="{row}">
          <el-image
            v-if="row.pict"
            style="width: 50px; height: 50px"
            :src="row.pict"
            fit="contain"
            :preview-src-list="[row.pict]"
          />
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Text" prop="text" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span v-if="row.text">{{ row.text }}</span>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column label="Price" prop="price" align="center" width="80">
        <template slot-scope="{row}">
          <span v-if="row.price">{{ row.price }}</span>
          <not-icon v-else />
        </template>
      </el-table-column>
      <el-table-column
        label="Actions"
        align="center"
        min-width="240"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row,$index}">
          <el-button
            v-waves
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(row, $index)"
          >Edit</el-button>
          <el-button
            v-waves
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(row, $index)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="Type" prop="type">
          <el-select :value="temp.type" disabled class="filter-item"></el-select>
        </el-form-item>
        <template v-if="temp.type">
          <el-form-item label="Mode" prop="mode">
            <el-radio-group
              v-model="temp.mode"
              :disabled="['list_of_clicks', 'list_of_products'].includes(temp.type)"
            >
              <el-radio-button label="wrap" />
              <el-radio-button label="unwrap" />
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="temp.style" label="Style" prop="style">
            <el-radio-group
              v-model="temp.style"
              :disabled="['list_of_clicks', 'list_of_products'].includes(temp.type)"
            >
              <el-radio-button label="link" />
              <el-radio-button label="button" />
              <el-radio-button label="picture" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="Text">
            <el-input v-model="temp.text" />
          </el-form-item>
          <!-- <el-form-item v-if="temp.style === 'picture'" label="Pict">
            <image-upload />
          </el-form-item>-->
          <el-form-item label="Click">
            <el-input v-model="temp.click">
              <template slot="prepend">
                <div class="pic-prepend">
                  <el-select
                    v-model="temp.clickPrepend"
                    class="filter-item"
                    placeholder="Please select"
                  >
                    <el-option v-for="item in clickTypes" :key="item" :label="item" :value="item"></el-option>
                  </el-select>
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="temp.type === 'list_of_products'" label="Price">
            <el-input v-model="temp.price" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="closeDialog">Cancel</el-button>
        <el-button
          v-waves
          type="primary"
          @click="dialogStatus === 'add' ? addData() : editData()"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import NotIcon from './NotIcon.vue'
import waves from '@/directive/waves'
import ImageUpload from './ImageUpload.vue'
import Sortable from 'sortablejs'

export default {
  directives: { waves },
  components: { 'not-icon': NotIcon, ImageUpload },
  props: {
    data: {
      type: Object,
      default: () => { }
    },
  },
  emits: ['update'],
  data() {
    return {
      tableKey: 0,
      list: [],
      temp: {
        type: '',
        text: '',
        mode: 'wrap',
        style: 'link',
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        click: '',
        clickPrepend: '',
        price: '',
      },
      clickTypes: ['http://', 'https://', 'activity://', 'open://'],
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      sortdialogable: null,
    }
  },
  mounted() {
    this.$nextTick(() => this.list.length && this.setDialogTableSort())
  },
  methods: {
    /* 重置 temp */
    resetTemp() {
      this.temp = {
        type: this.data.type,
        mode: this.data.mode,
        style: this.data.style,
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        text: '',
        click: '',
        clickPrepend: '',
        price: '',
      }
    },
    /* 打开 弹窗 (创建) */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 添加 */
    addData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const item = this.formatData(this.temp)
          // console.log(item)
          this.list.push({
            ...item,
            id: `${Math.random().toString().slice(2)}_${Date.now()}`
            // id: `${this.list.length + 1}`
          })
          this.updateListItem()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Add Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /* 打开 弹窗 (更新)) */
    handleUpdate(row, $index) {
      for (const k in row) {
        this.temp[k] = row[k] || '';
        if (this.clickTypes.some(item => this.temp['click'].includes(item))) {
          const arr = this.temp['click'].split('//');
          this.temp['clickPrepend'] = arr[0] + '//';
          this.temp['click'] = arr[1];
        }
      }
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 编辑 */
    editData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const item = this.formatData(this.temp)
          const index = this.list.findIndex(m => m.id === this.temp.id)
          this.list[index] = { ...item, id: this.list[index].id };
          this.updateListItem()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /* 删除 */
    handleDelete(row, $index) {
      const index = this.list.findIndex(item => item.id === row.id);
      this.list.splice(index, 1)
      this.updateListItem();
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
    },
    closeDialog() {
      this.dialogFormVisible = false,
        this.resetTemp()
    },
    formatData(data) {
      let item = {};
      switch (data.type) {
        case 'list_of_clicks':
          item = {
            text: data.text,
            pict: data.style === 'picture' ? data.pict : '',
            click: data.clickPrepend + data.click,
          }
          break;
        case 'list_of_products':
          item = {
            price: data.price,
            text: data.text,
            pict: data.pict,
            click: data.clickPrepend + data.click,
          }
          break;
      }
      return item;
    },
    setDialogTableSort() {
      if (!this.$refs.dragSubTableRef) return;
      const el = this.$refs.dragSubTableRef.$el.querySelectorAll('#sub-table-item .el-table__body-wrapper > table > tbody')[0];
      this.sortdialogable = Sortable.create(el, {
        animation: 180,
        delay: 0,
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        draggable: '.el-table__row',
        setData: (dataTransfer) => {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow);
          this.updateListItem();
        }
      })
    },
    updateListItem() {
      this.$nextTick(() => {
        this.$emit('update', {
          ...this.defaultData,
          items: this.list.map(item => {
            delete item.id;
            return item;
          })
        })
      })
    }
  },
  computed: {
    defaultData() {
      return {
        sid: this.data.sid,
        type: this.data.type,
        style: this.data.style,
        mode: this.data.mode,
      }
    }
  },
  watch: {
    'data': {
      handler: function (val) {
        this.list = val.items.map((item, index) => ({
          ...item,
          id: `${Math.random().toString().slice(2)}_${Date.now()}`
        }));
        this.temp = {
          ...this.temp,
          type: val.type,
          mode: val.mode,
          style: val.style,
        }
      },
      immediate: true
    },
  }
}
</script>

<style scoped>
.pic-prepend {
  width: 100px;
}
</style>
